#pragma once
#include <iostream>
#include <string>
#include <list>
#include <functional>
#include <unistd.h>
#include "tcp_socket.hh"
class reactor_server_t;
// 事件与方法的联系对象
class connection_t
{
    friend class reactor_server_t;
    // 业务处理方法
    using handler_t = std::function<bool(connection_t *)>;

public:
    connection_t(int fd, reactor_server_t *p_back) : _fd(fd), _p_back(p_back) { ; }
    ~connection_t() { close(_fd); }

public:
    // 外部提供IO方法
    void set_read_handler(const handler_t &new_handler)
    {
        _read_handler = new_handler;
    }
    void set_write_handler(const handler_t &new_handler)
    {
        _write_handler = new_handler;
    }
    void set_error_handler(const handler_t &new_handler)
    {
        _error_handler = new_handler;
    }
    // 时间就绪时的回调
    bool read() { return _read_handler(this); }
    bool write() { return _write_handler(this); }
    bool error() { return _error_handler(this); }
    const std::list<std::string> *get_packages()
    {
        return &_packages;
    }
    void append_to_write_buffer(const std::string &str)
    {
        _write_buffer += str;
    }
    int get_fd()
    {
        return _fd;
    }
    bool is_write_buffer_empty()
    {
        return _write_buffer.empty();
    }

private:
    // socket_fd
    int _fd;
    // buffer for fd
    std::string _read_buffer;
    std::string _write_buffer;
    // handler func
    handler_t _read_handler;
    handler_t _write_handler;
    handler_t _error_handler;
    // packages
    std::list<std::string> _packages;

public:
    // reactor
    reactor_server_t *_p_back;
};